package com.lc.config;

import com.lc.constant.Constants;
import com.lc.exception.BusinessException;
import com.lc.pojo.UmsUser;
import com.lc.result.ResultEnum;
import com.lc.utils.JWTUtil;
import com.lc.utils.ThreadVariablesUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器
 */

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(Constants.Redis.PREFIX_TOKEN);

        //判断token是否为空
        if(token== null || token.isEmpty()){
            throw new BusinessException(ResultEnum.AUTH_TOKEN_EMPTY);
        }

        //校验token是否失效
        if (!JWTUtil.checkToken(token)) {
            throw new BusinessException(ResultEnum.AUTH_USER_NOT_LOGIN);
        }

        //给token续命
        UmsUser umsUser = JWTUtil.parseToken(token);
        //使用本地线程ThreadLocal来存储用户信息
        ThreadVariablesUtil.setThreadData(umsUser);

        String newToken = JWTUtil.createToken(umsUser);
        //修改请求的信息
        response.setHeader(Constants.Redis.PREFIX_TOKEN,newToken);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
